package net.gyapp.markim.module.contact;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.easyder.wrapper.base.adapter.ViewHelper;
import com.easyder.wrapper.base.listener.OnViewHelper;
import com.easyder.wrapper.base.view.WrapperStatusActivity;
import com.easyder.wrapper.core.model.BaseVo;
import com.easyder.wrapper.core.scheduler.Task;
import com.easyder.wrapper.core.scheduler.TaskScheduler;

import net.gyapp.markim.ApiConfig;
import net.gyapp.markim.R;
import net.gyapp.markim.core.ImHelper;
import net.gyapp.markim.core.entity.GroupEntity;
import net.gyapp.markim.core.entity.MemberEntity;
import net.gyapp.markim.module.basic.base.CommonPresenter;
import net.gyapp.markim.module.contact.adapter.ContactsAdapter;
import net.gyapp.markim.module.contact.adapter.InviteGroupAdapter;
import net.gyapp.markim.module.contact.vo.ContactHeaderEntity;
import net.gyapp.markim.module.contact.vo.GroupMemberVo;
import net.gyapp.markim.module.contact.vo.TempInviteGroupBean;
import net.gyapp.markim.utils.CommonTools;
import net.gyapp.markim.utils.RequestParams;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import me.winds.widget.usage.TitleView;

/**
 * Author:  winds
 * Data:    2018/10/9
 * Version: 1.0
 * Desc:
 */


public class InviteGroupActivity extends WrapperStatusActivity<CommonPresenter> {

    @BindView(R.id.mRecyclerView)
    RecyclerView mRecyclerView;

    String groupNumber;
    InviteGroupAdapter adapter;
    List<GroupMemberVo.GroupUsersBean> groupList = new ArrayList<>();

    public static Intent getIntent(Context context, String groupNumber, ArrayList<GroupMemberVo.GroupUsersBean> list) {
        return new Intent(context, InviteGroupActivity.class).putExtra("groupNumber", groupNumber).putExtra("list", list);
    }

    @Override
    protected int getViewLayout() {
        return R.layout.common_recycler;
    }

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        super.initView(savedInstanceState, titleView, intent);
        titleView.setCenterText("选择联系人");
        titleView.setText(titleView.title_tv_left, "取消");
        titleView.setText(titleView.title_tv_right, "确定");
        titleView.title_iv_left.setVisibility(View.GONE);
        titleView.setChildClickListener(titleView.title_tv_left, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressedSupport();
            }
        });
        titleView.setChildClickListener(titleView.title_tv_right, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onClickConfirm();
            }
        });

        groupNumber = intent.getStringExtra("groupNumber");
        groupList.addAll((ArrayList<GroupMemberVo.GroupUsersBean>) intent.getSerializableExtra("list"));

        adapter = new InviteGroupAdapter();
        mRecyclerView.setAdapter(adapter);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
        mRecyclerView.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter baseQuickAdapter, View view, int position) {
                MultiItemEntity item = adapter.getItem(position);
                if (item instanceof MemberEntity) {
                    adapter.toggleSelection(item);
                    adapter.notifyDataSetChanged();
                }
            }
        });
        adapter.addHeaderView(getSearchView());
    }

    private void onClickConfirm() {
        if(adapter.getSelectedCount() > 0) {
            List<MemberEntity> list = adapter.getSelection();
            presenter.setNeedDialog(true);
            presenter.postJsonData(ApiConfig.API_INVITE_JOIN_GROUP, new RequestParams().put("", JSON.toJSONString(new TempInviteGroupBean(groupNumber, list))).get(), BaseVo.class);
        }else {
            onBackPressedSupport();
        }
    }

    @Override
    protected void loadData(Bundle savedInstanceState, Intent intent) {
        getContactData();
    }

    @Override
    public void showContentView(String url, BaseVo dataVo) {
        super.showContentView(url, dataVo);
        if(url.contains(ApiConfig.API_INVITE_JOIN_GROUP)) {
            showToast("邀请成功");
            setResult(RESULT_OK);
            finish();
        }
    }

    private void getContactData() {
        TaskScheduler.execute(new Task<List<MultiItemEntity>>() {
            @Override
            public List<MultiItemEntity> doInBackground() throws InterruptedException {
                List<MultiItemEntity> list = new ArrayList<>();
                List<MemberEntity> tempList = new ArrayList<>();

                List<MemberEntity> friendList = ImHelper.getFriendList();

                if (friendList != null && friendList.size() > 0) {
                    for (int i = 0; i < friendList.size(); i++) {
                        MemberEntity entity = friendList.get(i);

                        if (!isContain(entity.memberId)) {
                            entity.firstLetter = CommonTools.getLetter(entity.nick).toUpperCase();
                            tempList.add(entity);
                        }
                    }
                }

                if (tempList != null && tempList.size() > 0) {
                    adapter.sort(friendList); //排序
                    //添加头部
                    ContactHeaderEntity entity = new ContactHeaderEntity(tempList.get(0).firstLetter, tempList.get(0).firstLetter, ContactsAdapter.TYPE_CONTACT_HEADER);
                    list.add(entity);
                    for (int i = 0; i < tempList.size(); i++) {
                        MemberEntity item = tempList.get(i);
                        if (!item.firstLetter.equalsIgnoreCase(entity.firstLetter)) {
                            entity = new ContactHeaderEntity(item.firstLetter, item.firstLetter, ContactsAdapter.TYPE_CONTACT_HEADER);
                            list.add(entity);
                        }
                        list.add(item);
                    }

                }

                return list;
            }

            @Override
            public void onSuccess(List<MultiItemEntity> result) {
                getStatusDelegate().removeStatus();
                adapter.setNewData(result);
            }
        });
    }

    private boolean isContain(String memberId) {
        boolean bool = false;
        for (int j = 0; j < groupList.size(); j++) {
            GroupMemberVo.GroupUsersBean bean = groupList.get(j);
            if (memberId.equals(bean.userId)) { //已添加到群组
                bool = true;
            }
        }
        return bool;
    }

    private View getSearchView() {
        return getHelperView(mRecyclerView, R.layout.hearder_search_input, new OnViewHelper() {
            @Override
            public void help(ViewHelper helper) {
                EditText etInput = helper.getView(R.id.et_input);
                etInput.setImeActionLabel("搜索", EditorInfo.IME_ACTION_SEARCH);
                etInput.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                    @Override
                    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                        if (actionId == EditorInfo.IME_ACTION_SEARCH && v.getId() == R.id.et_input) {
                            String s = v.getText().toString();
                            adapter.clearSelection();
                            if (!TextUtils.isEmpty(s)) {
                                search(String.format("%1$s%2$s%3$s", "%", s, "%"));
                            }else {
                                getContactData();
                            }
                        }
                        return false;
                    }
                });
            }
        });
    }

    private void search(final String s) {
        TaskScheduler.execute(new Task<List<MultiItemEntity>>() {
            @Override
            public List<MultiItemEntity> doInBackground() throws InterruptedException {
                List<MultiItemEntity> list = new ArrayList<>();
                List<MemberEntity> tempList = new ArrayList<>();

                List<MemberEntity> friendList = ImHelper.getFriendList(s);
                if (friendList != null && friendList.size() > 0) {
                    for (int i = 0; i < friendList.size(); i++) {
                        MemberEntity entity = friendList.get(i);
                        if (!isContain(entity.memberId)) {
                            entity.firstLetter = CommonTools.getLetter(entity.nick).toUpperCase();
                            tempList.add(entity);
                        }
                    }
                }

                if (tempList != null && tempList.size() > 0) {
                    adapter.sort(friendList); //排序
                    //添加头部
                    ContactHeaderEntity entity = new ContactHeaderEntity(tempList.get(0).firstLetter, tempList.get(0).firstLetter, ContactsAdapter.TYPE_CONTACT_HEADER);
                    list.add(entity);
                    for (int i = 0; i < tempList.size(); i++) {
                        MemberEntity item = tempList.get(i);
                        if (!item.firstLetter.equalsIgnoreCase(entity.firstLetter)) {
                            entity = new ContactHeaderEntity(item.firstLetter, item.firstLetter, ContactsAdapter.TYPE_CONTACT_HEADER);
                            list.add(entity);
                        }
                        list.add(item);
                    }
                }
                return list;
            }

            @Override
            public void onSuccess(List<MultiItemEntity> result) {
                adapter.setNewData(result);
            }
        });
    }
}
